package cn.edu.zafu.bigdata.lwg;

import java.io.*;
import java.util.Scanner; // 确保导入了Scanner类

public class TextFileOperations {

    // 将用户输入的文本写入到指定的文件中
    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取文件内容并将其打印到控制台
    public static void readFromFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到：" + fileName);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // 创建Scanner对象实例
        System.out.println("请输入您的学号：");
        String studentId = scanner.nextLine();
        String fileName = "files/" + studentId + ".txt"; // 根据学号创建文件名

        System.out.println("请输入要保存到文件的文本：");
        String content = scanner.nextLine(); // 获取用户输入的文本

        // 将文本写入文件
        writeToFile(fileName, content);

        // 读取并显示文件内容
        System.out.println("文件内容如下：");
        readFromFile(fileName);

        scanner.close(); // 关闭Scanner对象
    }
}